package {
import com.greatxin.utils.ColorUtils;

import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.utils.Dictionary;

/**
 * 可编辑格子
 * @author daichangxin
 */
public class GridDesign extends Sprite
{
	private var _gridHCount:uint = 20;
	private var _gridVCount:uint = 20;
	private var _gridItemWidth:uint = 20;
	private var _gridItemHeight:uint = 20;
	private var _grid:Grid;
	private var _front:Shape;
	
	private var _mapInfo:Dictionary;
	
	public function GridDesign()
	{
		this._grid = new Grid(this._gridHCount, this._gridVCount, this._gridItemWidth, this._gridItemHeight);
		addChild(this._grid);
		
		_front = new Shape();
		addChild(_front);
		
		this._mapInfo = new Dictionary();
		for (var i : int = 0; i < this._gridVCount; i++) 
		{
			for (var j : int = 0; j < this._gridHCount; j++) 
			{
				_mapInfo[j + "-" + i] = 0;
			}
		}
		
		this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
		this.addEventListener(MouseEvent.CLICK, onClick);
	}

	private function onClick(event : MouseEvent) : void
	{
		var point:Point = getMouseDownGridInfo();
		this._front.graphics.beginFill(ColorUtils.getRandomColor());
		this._front.graphics.drawRect(point.x, point.y, this._gridItemWidth, this._gridItemHeight);
		
		var gridX:uint = point.x / this._gridItemWidth;
		var gridY:uint = point.y / this._gridItemHeight;
		
		this.updateGridMapInfo(gridX, gridY, false);
	}

	private function onMouseDown(event : MouseEvent) : void
	{
		this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
	}
	
	private function onMouseUp(event : MouseEvent) : void 
	{
		this.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		this.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
	}

	private function onMouseMove(event : MouseEvent) : void
	{
		var point:Point = getMouseDownGridInfo();
		
		this._front.graphics.beginFill(0x0);
		this._front.graphics.drawRect(point.x, point.y, this._gridItemWidth, this._gridItemHeight);
		
		var gridX:uint = point.x / this._gridItemWidth;
		var gridY:uint = point.y / this._gridItemHeight;
		
		this.updateGridMapInfo(gridX, gridY, true);
	}
	
	private function updateGridMapInfo(gridX:uint, gridY:uint, isTrue:Boolean):void
	{
		this._mapInfo[gridX + "-" + gridY] = isTrue? 1:0;
	}
	
	private function getMouseDownGridInfo():Point
	{
		var xPos:uint = Math.floor(this.mouseX / this._gridItemWidth) * this._gridItemWidth;
		var yPos:uint = Math.floor(this.mouseY / this._gridItemHeight) * this._gridItemHeight;
		
		return new Point(xPos, yPos);
	}
	
	public function getMapInfo():Dictionary
	{
		return _mapInfo;
	}
	
	public function get gridHCount():uint
	{
		return this._gridHCount;
	}
	
	public function get gridVCount():uint
	{
		return this._gridVCount;
	}
}
}
